local function tryStore()
    local top = peripheral.wrap("top")
    local bottom = peripheral.wrap("bottom")
    if top and peripheral.hasType(top, "inventory") then
        return turtle.dropUp()
    elseif bottom and peripheral.hasType(bottom, "inventory") then
        return turtle.dropDown()
    end
    return false
end

while true do
    repeat
        -- sleep 4gt
        sleep(0.2)
    until turtle.detect()

    turtle.dig()

    if turtle.getItemCount() >= 64 then
        local s = turtle.getSelectedSlot()
        local suc = tryStore()
        if not suc then
            if s < 16 then
                turtle.select(s + 1)
            else
                break
            end
        elseif s > 1 then
            for n = 1, s do
                turtle.select(n)
                tryStore()
            end
            turtle.select(1)
        end
    end

end
